import React from 'react';
import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonList,
  IonItem,
  IonLabel,
  IonBackButton,
  IonButtons,
} from '@ionic/react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useChatStore } from '../store/chat';

const ChatHistoryPage: React.FC = () => {
  const { histories, currentService } = useChatStore();
  const messages = histories[currentService] || [];

  const groupedMessages = messages.reduce((groups, message) => {
    const date = format(message.timestamp, 'yyyy-MM-dd', { locale: zhCN });
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(message);
    return groups;
  }, {} as Record<string, typeof messages>);

  const sortedDates = Object.keys(groupedMessages).sort((a, b) => 
    new Date(b).getTime() - new Date(a).getTime()
  );

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonBackButton defaultHref="/chat" />
          </IonButtons>
          <IonTitle>聊天记录</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent>
        {sortedDates.length === 0 ? (
          <div className="ion-padding ion-text-center">
            <IonLabel color="medium">暂无聊天记录</IonLabel>
          </div>
        ) : (
          <IonList>
            {sortedDates.map(date => (
              <React.Fragment key={date}>
                <IonItem>
                  <IonLabel color="medium">
                    {format(new Date(date), 'MM月dd日', { locale: zhCN })}
                  </IonLabel>
                </IonItem>

                {groupedMessages[date].map(message => (
                  <IonItem key={message.id} className={message.isBot ? 'bot-message' : 'user-message'}>
                    <IonLabel className="ion-text-wrap">
                      <p>{message.text}</p>
                      <p className="ion-text-end">
                        <small>{format(message.timestamp, 'HH:mm', { locale: zhCN })}</small>
                      </p>
                    </IonLabel>
                  </IonItem>
                ))}
              </React.Fragment>
            ))}
          </IonList>
        )}
      </IonContent>
    </IonPage>
  );
};

export default ChatHistoryPage;